package com.ty.user.starter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ty.user.starter.entity.Permission;
import com.ty.user.starter.entity.dto.PermissionDto;
import com.ty.user.starter.mapper.MenuMapper;
import com.ty.user.starter.mapper.PermissionMapper;
import com.ty.user.starter.mapper.RoleMapper;
import com.ty.user.starter.service.PermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * <p>
 * 用户角色菜单 服务实现类
 * </p>
 *
 * @author minku
 * @since 2021-10-16
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuMapper menuMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(PermissionDto dto) {
        this.delete(dto.getRoleId());
        // 验证菜单集合中是否存在重复的菜单权限设置
        long count = dto.getMenuIds().parallelStream().distinct().count();
        Assert.isTrue(dto.getMenuIds().size() == count, "菜单权限重复设置");
        // 验证菜单信息是否存在
        for (Long menuId : dto.getMenuIds()) {
            Assert.notNull(menuMapper.selectById(menuId), String.format("菜单id: %d 不存在", menuId));
        }
        // 异步循环保存
        dto.getMenuIds().parallelStream().forEach(menuId -> {
            Permission permission = new Permission();
            permission.setRoleId(dto.getRoleId());
            permission.setMenuId(menuId);
            baseMapper.insert(permission);
        });
    }

    /**
     * 尝试删除角色对应的菜单权限
     *
     * @param roleId 角色id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(long roleId) {
        Assert.notNull(roleMapper.selectById(roleId), "角色信息不存在");
        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.eq("role_id", roleId);
        baseMapper.delete(query);
    }
}
